#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <arpa/inet.h>


// ./t2 <port>
int main(int argc, char const *argv[])
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server_addr = {
        .sin_family = AF_INET,
        .sin_port = htons(atoi(argv[1])),
        .sin_addr.s_addr = inet_addr("10.35.161.15")
    };
    if(connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) !=0){
        perror("connect");
        return -1;
    }

    fd_set read_set;
    int n; // select() 返回结果
    char buf[1024] = "";
    while(1){
        FD_ZERO(&read_set);
        FD_SET(sockfd, &read_set); // 服务器响应数据时
        FD_SET(STDIN_FILENO, &read_set) ; // 读取键盘输入的数据

        n = select(sockfd+1, &read_set, NULL, NULL, NULL);
        if(n <=0 ){
            break;
        }

        if(FD_ISSET(STDIN_FILENO, &read_set)) {
            // 从键盘读取数据并发送给服务器
            fgets(buf, 1024,stdin);
            buf[strcspn(buf, "\n")] = 0;
            send(sockfd, buf, strlen(buf), 0);
            bzero(buf, 1024);
        }

        if(FD_ISSET(sockfd, &read_set)){
            // 读取服务器响应的数据
            if(recv(sockfd, buf, 1024, 0) > 0){
                printf("%s\n", buf);
                bzero(buf, 1024);
            }else{
                break;  // 服务器断开了
            }
        }
    }

    close(sockfd);
    
    return 0;
}
